package middleware

import (
	"fmt"
	// "bytes"
	// "io"
	"os"
	"strconv"

	// "strings"
	// "sync"
	"time"

	// "github.com/labstack/echo"
	// "github.com/labstack/gommon/color"
	// "github.com/valyala/fasttemplate"
	"oxy_server/module/log"
)

var gfile *os.File

func PathExists(path string) (bool, error) {
	_, err := os.Stat(path)
	if err == nil {
		return true, nil
	}
	if os.IsNotExist(err) {
		return false, nil
	}
	return false, err
}

func GetFileName(filetype string) (string, error) {
	year := time.Now().Year()                    //年
	month := fmt.Sprint(int(time.Now().Month())) //月
	day := time.Now().Day()
	filename := strconv.Itoa(year) + "-" + month + "-" + strconv.Itoa(day) + filetype
	return filename, nil
}

func CreateFile() (*os.File, error) {
	filename, err := GetFileName(".log")
	// Source
	_dir := "/log/" + filename
	exist, err := PathExists(_dir)
	if err != nil {
		log.Info("get dir error![%v]\n", err)
		return nil, err
	}
	if exist {
		// 打开文件
		file, err := os.OpenFile(_dir, os.O_WRONLY|os.O_APPEND, 0666)
		if err != nil {
			return nil, err
		}
		gfile = file
		return file, nil

	} else {
		// 创建文件
		file, err := os.Create(_dir)
		if err != nil {
		} else {
		}
		gfile = file
		return file, nil
	}
}

func GetFile() *os.File {
	return gfile
}
